package com.abc.http.example.api;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.*;

import com.abc.http.example.common.model.HttpResult;
import com.abc.http.example.common.model.User;
import com.abc.http.example.high.token.Token;
import com.abc.http.example.high.token.TokenParam;

import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: yansl.cn
 * @create: 2023-01-18 10:37
 */
@Slf4j
@RestController
@RequestMapping("high/token/api")
public class HighTokenAPI {

    @GetMapping("v1/token")
    public HttpResult v1Token(String appId, String secret) {

        log.info("GET生成token【APPID：{}，SECRET:{}】", appId, secret);

        Token token = new Token();
        token.setToken("TOKEN-GET-123456");
        token.setTimeExpire(120);
        return HttpResult.OK(token);
    }

    @PostMapping("v2/token")
    public HttpResult v2Token(@RequestBody TokenParam tokenParam) {
        log.info("POST生成token【APPID：{}，SECRET:{}】", tokenParam.getAppId(), tokenParam.getSecret());

        Token token = new Token();
        token.setToken("TOKEN-POST-123456");
        token.setTimeExpire(240);
        return HttpResult.OK(token);
    }

    /**
     * 返回 字符串
     *
     * @return
     */
    @GetMapping("get")
    public HttpResult get(String name, String token, HttpServletRequest request) {
        printToken(token, request);
        return HttpResult.OK(name);
    }

    /**
     * 返回 单对象
     *
     * @return
     */
    @GetMapping("getByUser")
    public HttpResult getByUser(String token, HttpServletRequest request) {
        printToken(token, request);
        return HttpResult.OK(new User("单对象", 123));
    }

    /**
     * 返回 列表
     *
     * @return
     */
    @GetMapping("list")
    public HttpResult list(String token, HttpServletRequest request) {
        printToken(token, request);
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            users.add(new User("对象" + i, 123 + i));
        }
        return HttpResult.OK(users);
    }

    /**
     * 提交 单对象
     *
     * @return
     */
    @PostMapping("createUser")
    public HttpResult createUser(@RequestBody User user, String token, HttpServletRequest request) {
        printToken(token, request);
        return HttpResult.OK(user);
    }

    /**
     * 输出Token 值
     * 
     * @param token
     * @param request
     */
    private void printToken(String token, HttpServletRequest request) {
        log.info("请求URL参数Token:{}", token);
        log.info("请求Header参数Token:{}", request.getHeader("Token"));
    }

}
